﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using DAL.Model;
using UI.Helper;

namespace UI.MasterData
{
    public partial class frmUnitOfMeasureManager : Form
    {
        private MasterSession _session;

        public frmUnitOfMeasureManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handle loading data on showing form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmUnitOfMeasureManager_Load (object sender, EventArgs e)
        {
            _session = new MasterSession();

            // get data for binding grid.
            _session.UnitOfMeasures.ToArray();
            var unitOfMeasures = _session.UnitOfMeasures.Local.ToBindingList();

            dgUnitOfMeasures.DataSource = unitOfMeasures;
            gvUnitOfMeasures.BestFitColumns();
        }

        /// <summary>
        /// Close form without saving changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spCancel_Click (object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Save changes and close form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spSave_Click (object sender, EventArgs e)
        {
            _session.CommitChanges();
            this.Close();
        }

        private void gvUnitOfMeasures_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            var unitOfMeasure = (UnitOfMeasure)gvUnitOfMeasures.GetRow(gvUnitOfMeasures.FocusedRowHandle);
            // if cannot get current row
            if (unitOfMeasure == null)
            {
                return;
            }

            gvUnitOfMeasures.ClearColumnErrors();

            if (string.IsNullOrEmpty(unitOfMeasure.Code))
            {
                gvUnitOfMeasures.SetColumnError(FormHelper.GetColumn(gvUnitOfMeasures, "Code"), "Nhập mã loại");
                e.Valid = false;
            }
            if (string.IsNullOrEmpty(unitOfMeasure.Name))
            {
                gvUnitOfMeasures.SetColumnError(FormHelper.GetColumn(gvUnitOfMeasures, "Name"), "Nhập tên loại");
                e.Valid = false;
            }
        }
    }
}
